### PACKAGE PREAMBLE ###

# Create a vector of package names
packages <- c("dplyr", "ggplot2", "tidyr", "tidyverse", "data.table", "readxl", "foreign", "devtools", "fixest", "sandwich", "modelsummary", "kableExtra")

installed_packages <- packages %in% rownames(installed.packages())
if (any(installed_packages == FALSE)) {
  install.packages(packages[!installed_packages])
}

# Packages loading
invisible(lapply(packages, library, character.only = TRUE))
rm(packages, installed_packages)

options(modelsummary_format_numeric_latex = "plain")
f <- function(x) format(x, digits = 3, nsmall = 2, scientific = FALSE)

getwd()
setwd(dir = "/Users/jmc4qg/The Lab Dropbox/Jonathan Colmer/ShotSpotter_env/Journal_submissions/ReStat/Replication Folder/")
mydata <- read.dta("Analysis Data/NIBRS_analysis.dta")

# Panel A: Mean Temperature 

T1_Mean <- feols(homicide_pc~ tMean + prec , data=mydata)
summary(T1_Mean, cluster="fips")
T2_Mean <- feols(homicide_pc~ tMean + prec | sample_month + week + dow, data=mydata)
summary(T2_Mean, cluster="fips")
T3_Mean <- feols(homicide_pc~ tMean + prec | state_sample_month + week + dow, data=mydata)
summary(T3_Mean, cluster="fips")
T4_Mean <- feols(homicide_pc~ tMean + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_Mean, cluster="fips")

models <- list(T1_Mean, T2_Mean, T3_Mean, T4_Mean)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_A1/Table_A1_Panel_A.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

# Panel B: Max Temperature 

T1_Max <- feols(homicide_pc~ tMax + prec , data=mydata)
summary(T1_Max, cluster="fips")
T2_Max <- feols(homicide_pc~ tMax + prec | sample_month + week + dow, data=mydata)
summary(T2_Max, cluster="fips")
T3_Max <- feols(homicide_pc~ tMax + prec | state_sample_month + week + dow, data=mydata)
summary(T3_Max, cluster="fips")
T4_Max <- feols(homicide_pc~ tMax + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_Max, cluster="fips")

models <- list(T1_Max, T2_Max, T3_Max, T4_Max)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_A1/Table_A1_Panel_B.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))

# Panel C: Min Temperature 

T1_Min <- feols(homicide_pc~ tMin + prec , data=mydata)
summary(T1_Min)
T2_Min <- feols(homicide_pc~ tMin + prec | sample_month + week + dow, data=mydata)
summary(T2_Min, cluster="fips")
T3_Min <- feols(homicide_pc~ tMin + prec | state_sample_month + week + dow, data=mydata)
summary(T3_Min, cluster="fips")
T4_Min <- feols(homicide_pc~ tMin + prec | ori_sample_month + week + dow, data=mydata)
summary(T4_Min, cluster="fips")

models <- list(T1_Min, T2_Min, T3_Min, T4_Min)
modelsummary(models, vcov = ~fips, output = "Figures and Tables/Table_A1/Table_A1_Panel_C.tex", fmt = f, stars = c('*' = 0.1, '**' = 0.05, '***' = 0.01))
